package com.example.dolgi;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

/**
 * 
 * @author dark-wizard
 *
 * This class makes us possible to execute direct SQL requests
 * This is Data Access Object.
 * It is cover for {@link SQLLiteManager} class, which provides info about table in DB
 */
public class UserDebtDAO {

	private SQLiteDatabase _database;
	private SQLLiteManager _dbManager;
	private String[] allColumns = {SQLLiteManager.COLUMN_ID, SQLLiteManager.COLUMN_USERNAME, SQLLiteManager.COLUMN_DEBT};
	
	public UserDebtDAO(Context context) {
		_dbManager = new SQLLiteManager(context);
	}
	/**
	 * opens the DB
	 * @throws SQLException
	 */
	public void open() throws SQLException {
		_database = _dbManager.getWritableDatabase();
	}
	/**
	 * closes th DB
	 */
	public void close() {
		_dbManager.close();
	}
	/**
	 * This function gets the user form DB cursor pointing to it
	 * @param cursor
	 * @return
	 */
	private User cursorToUser(Cursor cursor) {
		User user = new User(cursor.getInt(0));
		user.setUsername(cursor.getString(1));
		user.setDebt(cursor.getString(2));
		return user;
	}
	/**
	 * creating new user in DB
	 * @param name
	 * @param debt
	 * @return new User()
	 */
	public User createUser(String name, String debt) {
		ContentValues cv = new ContentValues();
		//pairs key-value to add to DB
		cv.put(SQLLiteManager.COLUMN_USERNAME, name);
		cv.put(SQLLiteManager.COLUMN_DEBT, debt);
		
		long insertId = _database.insert(SQLLiteManager.TABLE_NAME, null, cv);
		Cursor cursor = _database.query(SQLLiteManager.TABLE_NAME, allColumns, SQLLiteManager.COLUMN_ID + " = " + insertId, null, null, null, null);
		cursor.moveToFirst();
		User newUser = cursorToUser(cursor);
		cursor.close();
		System.out.println("User "+name+" with debt "+debt + " created successfully!");
		
		return newUser;
	}
	/**
	 * deletes user from DB
	 * (thank you, captain Evidence!)
	 * @param user
	 */
	public void deleteUser(User user) {
		System.out.println("Debt \""+user.getDebt()+"\" from user \""+user.getUsername()+"\" was deleted!");
		_database.delete(SQLLiteManager.TABLE_NAME, SQLLiteManager.COLUMN_ID +"="+ user.getId(),null);
	}
	/**
	 * allows us to get all users from DB
	 * Maybe need to modify this method to add ability to sum everyone's debt
	 * @return
	 */
	public List<User> getAllUsers() {
		List<User> list = new ArrayList<User>();
		Cursor cur = _database.query(SQLLiteManager.TABLE_NAME, allColumns, null, null, null, null, null);
		cur.moveToFirst();
		
		while (!cur.isAfterLast()) {
			User user = cursorToUser(cur);
			list.add(user);
			cur.moveToNext();
		}
		cur.close();
		return list;
	}

}
